/*
 * @Author: 谢陈洁
 * @Date: 2025-07-14 11:24:54
 * @LastEditors: 谢陈洁
 * @LastEditTime: 2025-07-19 13:30:14
 * @Description: useFormDialog hooks 封装
 * @Params: T 泛型 表单数据类型
 * @Return: { dialogVisible, formData, dialogTitle, openDialog }
 */
export function useFormDialog<T = any>(

  saveApi: (data: T) => Promise<any>,
  successCallback?: (params?: T) => void
) {
  const dialogVisible = ref(false)
  const formData = ref<T>({} as T)
  const formRef = ref()
  const dialogTitle = ref('新增')

  const openDialog = (row?: T, title?: string) => {
    formData.value = row ? { ...row } : ({} as T)
    dialogTitle.value = title || (row ? '编辑' : '新增')
    dialogVisible.value = true
  }
  const closeDialog = () => {
    formData.value = {} as T
    dialogVisible.value = false
  }
  // 弹出框确认按钮点击事件
  const handleSubmit = async() => {
    try {
      await formRef.value?.handleSubmit()
    } catch (error) {
      console.error('提交失败:', error)
    }
  }
  const handleSubmitSuccess = async (data: T) => {
    console.log('handleSubmitSuccess', data)
    try {
      const res = await saveApi(data)
      ElMessage.success(res?.message || '保存成功')
      closeDialog()
      successCallback?.()
    } catch (error) {
      console.error('提交失败:', error)
    }
  }

  return {
    dialogVisible,
    formRef,
    formData,
    dialogTitle,
    openDialog,
    closeDialog,
    handleSubmit,
    handleSubmitSuccess,
  }
}
